<?php
/**
* Project: VsPhpFm 
* Package: VsCore
* File: db.php
*
* Version: 1.0
* Date: 30th August, 2007
* ------------------------
*
* Author: Ivan i. Atanasov johnny2000@abv.bg
*
*/
class VsDatabase {

	private static $_Instance = NULL;

	private $_dbLink = NULL;
	private $_error = NULL;
	
	static function Instance() {
		if(!self::$_Instance)
			self::$_Instance = new VsDatabase();

		return self::$_Instance;
	}
	//=================================================================
	
	function query($query, $toUtf8=true) {
		if(!$this->_dbLink) {
			//echo "VsDatabase::query()";

			return;
		}
		
		if($toUtf8)
			$query = iconv("utf8", "cp1251", $query);
		
		$res = mysql_query($query, $this->_dbLink);
		if(mysql_error())
			$this->_error = mysql_error();
		//echo "Num Rows:	".mysql_num_rows($res)."<br />";
		return $res;
	}
	//================================================================
	
	function records($res) {
		return mysql_fetch_assoc($res);
	
	}
	//=================================================================
	
	function error() {
		return $this->_error;
	}
	//==================================================================
	
	private function __construct() {
		global $config;
	
		if(!is_array($config['database'])) {
			$this->_error = "Database is not configured !";
		}
		else {
			$this->initNative();

		}
    }
	//=================================================================

	private function initNative() {
		global $config;
		
		$this->_dbLink = mysql_connect($config['database']['host'], $config['database']['user'], $config['database']['password']);
		if(!$this->_dbLink) {
			$this->_error = "Host, User or Password are not Valid !";
			
			return;
		}
	
		if(!mysql_select_db($config['database']['name'], $this->_dbLink)) {
			$this->_error = "Cannot select Database ! \"".$config['database']['name']."\"";
			
		}
		else {
			mysql_query("SET NAMES 'cp1251'");
		}
	}
	//===================================================================
};

?>
	